// import {renderToString} from 'react-dom/server'
// import React from 'react';
// import ReactDOM from 'react-dom';
// import { createStore, applyMiddleware, compose } from 'redux';
// import thunk from 'redux-thunk';
// import { Provider } from 'react-redux';
// import {StaticRouter} from 'react-router-dom';

// import reducer from '../src/reducers/index';
// import App from '../src/App';
// import {} from '../src/api/util';


// import express from 'express';
var express = require('express');
const path = require('path');
let app = express();
const http = require('http').Server(app);
let io = require('socket.io')(http);
var person = require('./person');
var roomList = require('./roomList');
var connectMsg = require('./connectMsg');


//********************service render start */
// const store = createStore(reducer,compose(
//     applyMiddleware(thunk),
// ));

// app.use((req, res, next) => {

//     if (req.url.startsWith('/api/')) {
//         return next();
//     }
//     var context = {};
//     const mark = renderToString(
//         <Provider store={store}>
//             <StaticRouter
//                 location={req.url}
//                 context={context}
//             >
//                 <App />
//             </StaticRouter>
//         </Provider>
//     );
//     res.send(mark);
// });

//**************************service rander end */


var port = 3000;
console.log(process.env.NODE_ENV);



//=================socket==========================
let hashSocket = {};

io.on('connection', socket => {
    hashSocket[socket.id] = socket;
    let _userName = null; //登录人名称.
    person.addUser(socket.id);

    //用户登录.
    socket.on(connectMsg.USER_LOGIN, (userName, fn) => {
        console.log('user login');
        fn = detailFun(fn);
        if (_userName == null) { //未登录.
            person.changeName(socket.id, userName);
            _userName = userName;
        }
        //返回登录消息.
        fn(success());

        // socket.emit(connectMsg.USER_LOGIN, success(person.getUserByKey(socket.id)));

        // //广播登录的用户信息
        // socket.broadcast.emit(connectMsg.USER_LOGIN, success({
        //     userName: userName,
        //     userCount: person.userCount()
        // }));
    });

    //用户退出.
    socket.on(connectMsg.USER_LOGOUT, (fn) => {
        console.log('user logout');
        fn = detailFun(fn);
        let user = person.getUserByKey(socket.id);

        userLeaveRoom(user); //登出房间.

        if (_userName !== null) {
            person.changeName(socket.id, null);
            _userName = null;
        }
        //已经登出
        fn(success());
        //socket.emit(connectMsg.USER_LOGOUT, success());
    });

    //获取房间列表
    socket.on(connectMsg.GET_ROOM_LIST, (fn) => {
        var arr = roomList.getRoomList();
        fn(success(arr));
        //socket.emit(connectMsg.GET_ROOM_LIST, success(arr));
    });

    //新增房间
    socket.on(connectMsg.ADD_ROOM, (roomName, fn) => {
        fn = detailFun(fn);

        let user = person.getUserByKey(socket.id);

        userLeaveRoom(user); //新增房间要进入对应房间中,先离开之前的房间.

        let obj = roomList.addRoom(roomName, user);

        if (obj) {

            fn(success(obj));
            socket.emit(connectMsg.ADD_ROOM, success(obj));
            socket.broadcast.emit(connectMsg.ADD_ROOM, success(obj));
        } else {
            //err
            fn(err());
            socket.emit(connectMsg.ADD_ROOM, err());
        }

    });

    //删除房间
    socket.on(connectMsg.REMOVE_ROOM, (key, fn) => {
        let user = person.getUserByKey(socket.id);
        if (roomList.removeRoom(key, user)) {
            fn(success(key));
            console.log('删除房间' + key);
            socket.emit(connectMsg.REMOVE_ROOM, success(key));
            socket.broadcast.emit(connectMsg.REMOVE_ROOM, success(key));
        } else {
            fn(err(null, '还有其他用户在房间内'));
            socket.emit(connectMsg.REMOVE_ROOM, err());
        }
    });

    //获取房间详情 获取详情则认为人进入房间.
    socket.on(connectMsg.GET_ROOM_INFO, (key, fn) => {
        var room = roomList.getRoomInfo(key);
        var user = person.getUserByKey(socket.id);

        var leaveRoom = roomList.leaveRoom(user);

        if (leaveRoom != null) {
            pushRoomChange(leaveRoom);
            if (leaveRoom.personList.length == 0) {
                //房间里是否还有人.
            }
        }

        roomList.addPerson(room, user);
        //console.log('获取房间详情', room);
        pushRoomChange(room);

        if (room)
            fn(success(room));
        else
            fn(err());
    });

    //离开房间.
    socket.on(connectMsg.LEAVE_ROOM, fn => {
        fn = detailFun(fn);
        var user = person.getUserByKey(socket.id);
        if (user == null) {
            fn(err(null, '没有找到该人员'));
            return;
        }
        console.log(socket.id + '离开房间' + user.roomKey);
        var leaveRoom = roomList.leaveRoom(user);
        if (leaveRoom != null) { //房间里是否还有人.
            pushRoomChange(leaveRoom);
            if (leaveRoom.personList.length == 0) {
                //房间里是否还有人
            }
        }
        if (leaveRoom == null) {
            fn(err(null, '该人员没有进房间'));
            return;
        }

        fn(success(leaveRoom));
    });

    //对画板添加内容
    socket.on(connectMsg.ADD_DRAW_INFO, (drawInfo, fn) => {
        fn = detailFun(fn);
        var user = person.getUserByKey(socket.id);
        if (user == null || user.roomKey == null) return;
        console.log(user.roomKey + '添加线条');
        var room = roomList.getRoomInfo(user.roomKey);
        if (!room) return err(undefined, '没有找到对应房间');
        drawInfo.userName = _userName;
        room.drawInfoList.push(drawInfo);
        //广播.
        for (let s = 0; s < room.personList.length; s++) {
            const user = room.personList[s];
            let _socket = hashSocket[user.key];
            if (_socket)
                _socket.emit(connectMsg.ADD_DRAW_INFO, drawInfo);
        }

        fn(success());
    });

    socket.on('disconnect', function () {
        console.log('user disconnected');
        var user = person.getUserByKey(socket.id);

        userLeaveRoom(user); //离开房间.

        person.deleteUser(socket.id);
        socket.broadcast.emit(connectMsg.USER_LOGIN, err({
            key: socket.id,
            userName: _userName,
            userCount: person.userCount()
        }, '用户断开连接'));
    });

    console.log('a user connected:' + socket.id);
});


http.listen(port, () => {
    console.log('服务已启动,http://localhost:' + port);
});

//房间信息变动 推送 (人员退出,人员进入.)
function pushRoomChange(roomInfo) {
    for (const key in hashSocket) {
        const socket = hashSocket[key];
        socket.emit(connectMsg.PUSH_ROOM_INFO_CHANGE, roomInfo);
    }
}

function userLeaveRoom(user) {
    if (user && user.roomKey != null) {
        var leaveRoom = roomList.leaveRoom(user);
        if (leaveRoom != null) { //离开房间的最新详情.
            pushRoomChange(leaveRoom);
            if (leaveRoom.personList.length == 0) {
                //房间里是否还有人 
                //超过N分钟没有的房间自动删掉...TODO
            }
        }
        return leaveRoom;
    }
    return null;
}

function detailFun(fn) {
    if (typeof fn !== 'function')
        fn = function () { }
    return fn;
}

function success(data = null, msg = '成功', number = 1) {
    let obj = {
        code: number,
        msg
    };
    if (data != null) {
        obj.data = data;
    }
    return obj;
}

function err(data = null, msg = '失败', number = 0) {
    let obj = {
        code: number,
        msg
    };
    if (data != null) {
        obj.data = data;
    }
    console.log(JSON.stringify(obj));
    return obj;
}